package org.marsdone.demo.aliyunapi

import com.aliyun.openservices.log.Client
import com.aliyun.openservices.log.common.LogGroupData
import com.aliyun.openservices.log.common.LogItem
import com.aliyun.openservices.log.exception.LogException
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest

@SpringBootTest
class AliyunApiApplicationTests {


	private final static String host = "cn-hangzhou.log.aliyuncs.com"
	private final static String accessId = "your access id"
	private final static String accessKey = "your access key"

	private final static String project = "your project"
	private final static String logStore = "your log store"

	@Test
	void test1() {
		def client = new Client(host, accessId, accessKey)

		int shardId = 0  // 只读取0号shard的数据
		String cursor
		try {
			// 获取最近1个小时接收到的第一批日志的cursor位置
			long fromTime = (int)(System.currentTimeMillis()/1000.0 - 3600)
			def res = client.GetCursor(project, logStore, shardId, fromTime)
			cursor = res.GetCursor()
			println "shard_id:$shardId Cursor:$cursor"
		} catch (LogException e) {
			e.printStackTrace()
		}

		while(true) {
			def logDataRes = client.BatchGetLog(project, logStore, shardId, 100, cursor)
			// 读取到的数据
			def logGroups = logDataRes.GetLogGroups()

            logGroups.each { LogGroupData groupData ->
                groupData.GetAllLogs().each { LogItem logItem ->
                    println logItem.ToJsonString()
                }
            }

			def nextCursor = logDataRes.GetNextCursor()  // 下次读取的位置
			println "The Next cursor:$nextCursor"
			if (cursor == nextCursor) {
				break
			}
			cursor = nextCursor
		}
	}

    @Test
    void test2() {
        def client = new Client(host, accessId, accessKey)

        String topic = ""

        try {
            String query = "class=c.z.s.d.ZcarezeDispatcherServlet and timed>300"
            int from = (int) (new Date().getTime() / 1000 - 10000)
            int to = (int) (new Date().getTime() / 1000 + 10)
            def logsResponse = client.GetLogs(project, logStore, from, to, topic, query, 10, 0, false)

            println "Returned log data count:${logsResponse.GetCount()}"

            for (def log : logsResponse.GetLogs()) {
                println "source : ${log.GetSource()}"

                LogItem item = log.GetLogItem()
                println "time : $item.mLogTime"

                for (def content : item.mContents) {
                    println "$content.mKey:$content.mValue"
                }
            }
        } catch (LogException e) {
            println "error code :${e.GetErrorCode()}"
            println "error message :${e.GetErrorMessage()}"
            throw e
        }
    }
}
